from app.db.mongoClient import ErrMongoClient, get_mongo_client
from app.globals.publicMethod import globalStrMd5
from loguru import logger
from . import dbSynPosUser, collectionUserList, collectionUserRoleList


def verifyUserNamePwd(userName, userPwd):
    '''
    校验用户名密码，存储token信息
    '''
    try:
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosUser][collectionUserList].find_one({'userName': userName})
        if res is not None:
            #判断是否启用/禁用该用户
            userState = str(res.get('userState'))
            if userState == 'disable':
                return False

            pwd = str(res.get('userPwd'))
            userId = str(res.get('userId'))
            userRoleId = str(res.get('userRoleId'))
            RelationDiningNoList = res.get('RelationDiningNoList')
            RelationStallNo = res.get('RelationStallNo')
            #print('!!',RelationStallNo)
            roleRes = mg_client[dbSynPosUser][collectionUserRoleList].find_one({'roleId': userRoleId})
            if roleRes is not None:
                userRoleName = roleRes.get('roleName')
                rolePower = roleRes.get('rolePower')
            if globalStrMd5(userPwd) == pwd:
                userInfo = {
                    'userId': userId,
                    'userRoleId': userRoleId,
                    'userRoleName': userRoleName,
                    'RelationDiningNoList': RelationDiningNoList,
                    'RelationStallNo': RelationStallNo,
                    'rolePower': rolePower
                }
                
                return userInfo
            else:
                logger.warning(f'用户登录失败,userName={userName},userId={userId},userRoleId={userRoleId}')
        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))


def getDiningsByUserId(userId):
    '''
    根据UserId找其下所管理的餐厅
    '''
    try:
        mg_client = get_mongo_client()
        res = mg_client[dbSynPosUser][collectionUserList].find_one({'userId': userId})
        if res is not None:
            RelationDiningNoList = res.get('RelationDiningNoList')
            return RelationDiningNoList

        return None
    except Exception as e:
        raise ErrMongoClient.data(str(e))
